package com.test.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.test.objects.Author;

public class LoginDAOImpl extends MyPageDAOBase implements LoginDAO {

	@SuppressWarnings("deprecation")
	public Author checkAuthor(String account, String password) {
		String sql = "SELECT * FROM author " +
					"WHERE account = '" + account + "' " + 
					"AND password = '" + password + "'";
		Author author = null;
		try{
			author = new SimpleJdbcTemplate(this.dataSource).
				queryForObject(sql, new ParameterizedRowMapper<Author>() {
					public Author mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Author author = new Author();
						author.setId(rs.getInt("Id"));
						author.setFirstname(rs.getString("firstname"));
						author.setFullname(rs.getString("fullname"));
						author.setAccount(rs.getString("account"));
						author.setPassword(rs.getString("password"));
						author.setDob(new Date(rs.getTimestamp("dob").getTime()));
						author.setAddress(rs.getString("address"));
						author.setImageUrl(rs.getString("imageUrl"));
						author.setDescription(rs.getString("description"));
						return author;
					}});
		}catch(EmptyResultDataAccessException erdaEx){
			System.err.println("[mypage-login] information of the account '" + account + "' does not match in the database");
		}
		return author;	
	}

	@SuppressWarnings("deprecation")
	public Author getAuthor(int id) {
		String sql = "SELECT * FROM author " +
					"WHERE Id = '" + id + "'";
		Author author = null;
		try {
			author = new SimpleJdbcTemplate(this.dataSource).
				queryForObject(sql, new ParameterizedRowMapper<Author>() {
					public Author mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Author author = new Author();
						author.setId(rs.getInt("Id"));
						author.setFullname(rs.getString("fullname"));
						author.setAccount(rs.getString("account"));
						author.setPassword(rs.getString("password"));
						author.setDob(new Date(rs.getTimestamp("dob").getTime()));
						author.setAddress(rs.getString("address"));
						author.setDescription(rs.getString("description"));
						return author;
					}});
		}catch(EmptyResultDataAccessException erdaEx){
			System.err.println("[mypage-login] author with id " + id + " can not be found in the database");
		}
		return author;
	}
	
}
